from flask import Flask, send_from_directory,render_template
from flask_socketio import SocketIO,emit
from flask_cors import CORS
from utils.dataloader import get_sample_data
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key ***'
app.config['STATIC_FOLDER'] = 'datasample'
app.config['STATIC_URL_PATH'] = '/static'

socketio = SocketIO(app, async_mode='eventlet')
CORS(app)  # 允许跨域请求

@app.route('/')
def home():
    print('/')
    return render_template('index.html')


@app.route('/home')
def home2():
    print('home')
    print("Current Working Directory:", os.getcwd())
    return 'Home Page'


@app.route('/static')
def static_file():
    filename = 'data1.npy'
    print(app.config['STATIC_FOLDER'], filename)
    return send_from_directory(app.config['STATIC_FOLDER'], filename)


@app.route('/sample')
def life():
    data = get_sample_data()
    return data.tolist()


@socketio.on('connect', namespace='/')
def connected_msg():
    print('客户端已连接')
    emit('server_response', {'message': '已连接到服务器'})


@socketio.on('request_data')
def handle_data():
    print('客户端请求数据')
    data = get_sample_data()
    print('数据加载成功，数据形状：', data.shape)

    #先发送第一帧
    first_flame = data[0].tolist()
    #将数据返回给客户端
    emit('data_response', {'frame': first_flame})


@socketio.on('disconnect')
def handle_disconnect():
    print('客户端连接已断开')

@app.errorhandler(404)
def not_found(error):
    return '您请求的页面不存在了，请确认后再次访问！', 404


if __name__ == '__main__':
    socketio.run(app, debug=True, port=59999, host='0.0.0.0')
